package rules

import (
	"ddl_checker/internal/config"
	"fmt"
	"strings"
)

// ExternalAPIRule 外部API检查规则 - 支持多个检查器
type ExternalAPIRule struct {
	validators []APIValidator
}

// Name 规则名称
func (r *ExternalAPIRule) Name() string {
	return "外部API检查"
}

// Check 执行检查
func (r *ExternalAPIRule) Check(data DDLCheckData) CheckResult {
	result := CheckResult{
		Status:  StatusPassed,
		Details: make([]string, 0),
	}

	// 获取所有启用的检查器
	enabledValidators := r.getEnabledValidators()
	if len(enabledValidators) == 0 {
		result.Details = append(result.Details,
			"### 外部API检查状态",
			"⚠️ 未配置API检查器，跳过检查",
			"",
		)
		result.Status = StatusSkipped
		return result
	}

	// 执行所有检查器
	hasFailure := false
	hasWarning := false

	for _, validator := range enabledValidators {
		apiResult := validator.Validate(data)

		// 添加检查器名称
		result.Details = append(result.Details, fmt.Sprintf("#### %s", validator.Name()))

		// 添加详细信息
		for _, detail := range apiResult.Details {
			result.Details = append(result.Details, detail)
		}

		// 添加分隔线
		result.Details = append(result.Details, "")

		// 检查结果
		switch apiResult.Conclusion {
		case APIConclusionFail:
			hasFailure = true
		case APIConclusionWarning:
			hasWarning = true
		}
	}

	// 确定最终结果
	if hasFailure {
		result.Status = StatusFailed
	} else if hasWarning {
		result.Status = StatusPassed // 警告不算失败，但需要显示
	} else {
		result.Status = StatusPassed
	}

	return result
}

// getEnabledValidators 获取所有启用的检查器
func (r *ExternalAPIRule) getEnabledValidators() []APIValidator {
	if r.validators == nil {
		r.validators = r.initializeValidators()
	}

	var enabled []APIValidator
	for _, validator := range r.validators {
		if validator.IsEnabled() {
			enabled = append(enabled, validator)
		}
	}

	return enabled
}

// initializeValidators 初始化所有检查器
func (r *ExternalAPIRule) initializeValidators() []APIValidator {
	// 从环境变量获取启用的检查器
	envValidators := config.GetString("ENABLED_VALIDATORS", "")
	var enabledValidators []string

	if envValidators != "" {
		enabledValidators = strings.Split(envValidators, ",")
		// 去除空格
		for i, name := range enabledValidators {
			enabledValidators[i] = strings.TrimSpace(name)
		}
	}

	// 根据配置创建检查器
	var validators []APIValidator
	for _, name := range enabledValidators {
		validator := CreateValidatorByName(name)
		if validator != nil {
			validators = append(validators, validator)
		}
	}

	return validators
}

// NewExternalAPIRule 创建外部API检查规则
func NewExternalAPIRule() *ExternalAPIRule {
	return &ExternalAPIRule{}
}
